package com.seniorproject.aims;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class UploadServlet
 */
@WebServlet("/UploadServletEmployee")
public class UploadServetEmployee extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	 private static final String UPLOAD_DIRECTORY = "upload";
	    private static final int THRESHOLD_SIZE     = 1024 * 1024 * 3;  // 3MB
	    private static final int MAX_FILE_SIZE      = 1024 * 1024 * 40; // 40MB
	    private static final int MAX_REQUEST_SIZE   = 1024 * 1024 * 50; // 50MB

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		 // checks if the request actually contains upload file
        if (!ServletFileUpload.isMultipartContent(request)) {
            PrintWriter writer = response.getWriter();
            writer.println("Request does not contain upload data");
            writer.flush();
            return;
        }
         
        
        // configures upload settings
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(THRESHOLD_SIZE);
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
         
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setFileSizeMax(MAX_FILE_SIZE);
        upload.setSizeMax(MAX_REQUEST_SIZE);
         
        // constructs the directory path to store upload file
        String uploadPath = getServletContext().getRealPath("")
            + File.separator + UPLOAD_DIRECTORY;
        // creates the directory if it does not exist
        File uploadDir = new File(uploadPath);
        
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }
         
        try {
            // parses the request's content to extract file data
            List formItems = upload.parseRequest(request);
            Iterator iter = formItems.iterator();
            String Path_temp = null;
             
            // iterates over form's fields
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                
                	String content_type = item.getContentType();
                	String[] content_type_temp = content_type.split("/");
                	
                	String file_extension = "."+content_type_temp[1];
                	
                	
                // processes only fields that are not form fields
                if (!item.isFormField()) {
                	
                	Date date = new Date();
                	String temp_year = date.getYear()+1900+"";
					String temp_month = date.getMonth()+1+"";
					String temp_date = date.getDate()+"";
					String temp_hour = date.getHours()+"";
					String temp_minute = date.getMinutes()+"";
					String temp_second = date.getSeconds()+"";
                	
                    String fileName =  temp_year+temp_month+temp_date+temp_hour+temp_minute+temp_second+file_extension;
                    String filePath = uploadPath + File.separator + fileName;
                 
                    File storeFile = new File(filePath);
                     
                    // saves the file on disk
                    item.write(storeFile);
                    System.out.println("FilePath:"+ filePath);
                    Path_temp = filePath;
                    System.out.println("storeFile :"+ storeFile.toString());
                }
            }
            request.setAttribute("message",Path_temp);
        } catch (Exception ex) {
            request.setAttribute("message", "There was an error: " + ex.getMessage());
            
        }
        getServletContext().getRequestDispatcher("/employee_import_result.jsp").forward(request, response);
    }
	

}
